import config from 'config.js'


function wxRequest(promise, resolve, reject,  _header) {
  let APIURL = config.BASE_API;
  wx.request({
    url: APIURL + promise.url,
    data: promise.data,
    method: promise.method,
    header: _header,
    success(res) {
        wx.hideLoading({
          success: (res) => {},
        })
        //跟服务器通信是否正常
        if (res.statusCode === 200) {
          if(res.data.code == 200) {
            resolve(res.data);
          }else if(res.data.code == 1001){
            var pages = getCurrentPages();
            var prevPage = pages[pages.length - 1];
            prevPage.setData({
              showLogin: true,
            })
          }else {
            resolve(res.data);
            wx.showToast({title: res.data.msg, icon: 'none',duration: 1500})
          }
        }else {
            wx.showToast({title: "网络异常",icon: 'none',duration: 1500 });
            resolve(res.data);
        }
    },
    fail(e){
        wx.showToast({title: "网络异常",icon: 'none',duration: 1500 });
        wx.hideLoading({
          success: (res) => {},
        })
        reject(e)
    }
  });

}


function Request(promise){
  let that = this;
  let _header = {
    'content-type': 'application/json' // 默认值
  };
  return new Promise(function (resolve, reject){
      let authorization = wx.getStorageSync('authorization');
      if(authorization) {
        _header.Authorization = authorization;
      }
      //只有首页也详情页不需要获取用户信息
      if(!config.FREE_API.includes(promise.url)) {
        if(wx.getStorageSync('userInfo').is_wechat_info == 0) {
            var pages = getCurrentPages();
            var prevPage = pages[pages.length - 1];
            prevPage.setData({
              showLogin: true,
            })
            return ;
        }
      }
      
      wxRequest(promise, resolve, reject, _header);

  })
}


module.exports = {
  Request: Request
}
